package leetcode;


import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Ghost on 2014/11/3 0003.
 */
public class Remove_Duplicates_from_Sorted_Array_II {
    public int removeDuplicates(int[] A) {
        HashMap<Integer,Integer> map = new LinkedHashMap<Integer, Integer>(A.length,(float)0.75,true);
        int total = 0;
        for (int aA : A) {
            if (!map.containsKey(aA)) {
                map.put(aA, 1);
                total++;
            } else if (map.containsKey(aA) && map.get(aA) < 2) {
                map.put(aA, 2);
                total++;
            }
        }
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        int i=0;
        for(Map.Entry entry: entries){
            int times = (Integer) entry.getValue();
            int key = (Integer) entry.getKey();
            while(times>0){
                A[i]=key;
                i++;
                times--;
            }
        }
        return total;
    }
    public static void main(String[] args){
        Remove_Duplicates_from_Sorted_Array_II remove_duplicates_from_sorted_array_ii = new Remove_Duplicates_from_Sorted_Array_II();
        int[] A = {1,2};
        int x = remove_duplicates_from_sorted_array_ii.removeDuplicates(A);
        for(int i=0;i<x;i++){
            System.out.print(" "+A[i]);
        }

    }
}
